/*
 * sort.c
 *
 *  Created on: Jul 17, 2021
 *      Author: dbw
 */

#define LOG_TAG     "example_algorithm"
#define LOG_LEVEL    LOG_LEVEL_VERBOSE
#include "logger.h"

#include "examples.h"

#include <stdint.h>
#include <stdlib.h>
#include "math_util.h"
#include "stack_monitor.h"

#ifdef EXAMPLE_SHOW_ARITHMETIC

static int int_compare(const void *d1, const void *d2)
{
    return *(int *)d1 - *(int *)d2;
}

static void print_int_array(int *buf, int len, const char *desc, int align)
{
    LOG_V("%s", desc);

    for (int i = 0; i < len; i++)
    {
        if (i % 16 == 0 && i != 0)
        {
            printf("\r\n");
        }

        printf("%*d ", align, buf[i]);
    }
    printf("\r\n");
}

void sort_example(void)
{
#define DATA_SIZE   1024

    static int data[DATA_SIZE];

    LOG_I("test sort");

    /* 倒序初始化数组, 因为qsort是顺序排序 */
    for (int i = 0; i < DATA_SIZE; i++)
    {
        data[i] = DATA_SIZE - i - 1;
    }

    qsort(data, DATA_SIZE, sizeof(int), int_compare);

    print_int_array(data, MATH_MIN(50, DATA_SIZE), "qsort result:", 3);
}

void mean_filter_example(void)
{
#define GAP     1

    int data[] = {9, 8, 1, 55, 8, 7};
    int mean;
    int num;

    LOG_I("test mean filter");

    /* 先排好序, 以便后续取中值 */
    qsort(data, ARRAY_SIZE(data), sizeof(int), int_compare);

    /* 取中值 */
    num = ARRAY_SIZE(data) - 2 * GAP;
    assert(num > 0);
    mean = 0;
    for (int i = GAP; i < ARRAY_SIZE(data) - GAP; i++)
    {
        mean += data[i];
    }
    mean /= num;

    print_int_array(data, ARRAY_SIZE(data), "after sort:", 0);
    LOG_D("mean value:%d", mean);
}

void algorithm_example_run(void)
{
    sort_example();
    mean_filter_example();
}

#else

void algorithm_example_run(void)
{

}

#endif /* EXAMPLE_SHOW_ARITHMETIC */
